package com.onclick.webchat.websocket;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.onclick.webchat.model.PushedMessage;
import com.onclick.webchat.websocketInterface.LoginService;
import com.onclick.webchat.websocketInterface.UserSocketIntface;



@Component
public class MyWebSocketHandler extends TextWebSocketHandler implements UserSocketIntface {
    private static final Map<String,WebSocketSession> users=new ConcurrentHashMap<>();
//    @Autowired
//	LoginService loginservice;
	@Override
	public void afterConnectionEstablished(WebSocketSession session) {
		// TODO Auto-generated method stub
		String privateId = (String) session.getAttributes().get("privateId");
		String username = "123";
		if (users.get(privateId)==null) {
			users.put(privateId, session);
			JSONObject msgObject = new JSONObject();
			msgObject.put("From", 0);
			msgObject.put("loginName", username);
			msgObject.put("color", "red");
			//通知相关好友，上线...
			System.out.println("id:"+privateId+"上线了");
			
		}
	}

	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) {
		if(message.getPayloadLength() == 0) {return;};
		PushedMessage msg = JSONObject.parseObject(message.getPayload().toString(), PushedMessage.class);
		LocalDateTime time = LocalDateTime.now();
		msg.setPushDate(time.toString());
		if (msg.getIsFlock()) {
			//发群操作
		}else {
			this.sendMessageToUser(msg.getPrivateId(), new TextMessage(JSON.toJSONBytes(msg)));
		}
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void broadcast(TextMessage message) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void sendMessageToUser(String uid, TextMessage message) {
		WebSocketSession session = users.get(uid);
		if (session != null) {
			try {
				session.sendMessage(message);
				//记录聊s天记录
				
			} catch (IOException e) {
				
				e.printStackTrace();
			}
		}else {
			//不在线的处理
		}
		
	}

	@Override
	public void pushMessageToFlock(String flockUid, TextMessage message) {
		//发送到群
		
		
	}
    
    
}
